<template>
  <el-date-picker
    v-model="date"
    type="daterange"
    start-placeholder="开始日期"
    end-placeholder="结束日期"
    @change="changeDate"
  />
</template>

<script setup>
import { reactive, ref, watch, onMounted, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useBaseParamStore } from '@/stores/baseParams'

const baseParamStore = useBaseParamStore()

const route = useRoute()
const router = useRouter()

const date = ref()

const formattedDate = (date) => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0') // 月份从0开始
  const day = String(date.getDate()).padStart(2, '0')

  return `${year}-${month}-${day}`
}
const changeDate = (e) => {
  const date1 = new Date(e[0])
  const date2 = new Date(e[1])

  const newQuery = {
    ...route.query,
    startDate: formattedDate(date1), // 替换或新增 rearerId 参数
    endDate: formattedDate(date2)
  }

  // 使用 router.replace 更新地址栏，不触发页面刷新
  router.replace({
    path: route.path,
    query: newQuery
  })

  setTimeout(() => {
    location.reload()
  }, 100)
}

// 获取今天和一周后的日期
const getOneWeekRange = () => {
  const today = new Date()
  const preWeek = new Date(today)
  preWeek.setDate(today.getDate() - 7)
  return [preWeek, today]
}

if (route.query.startDate && route.query.endDate) {
  date.value = [route.query.startDate, route.query.endDate]
  baseParamStore.baseParam.pickTime = [route.query.startDate, route.query.endDate]
} else {
  date.value = getOneWeekRange()
  baseParamStore.baseParam.pickTime = [formattedDate(date.value[0]), formattedDate(date.value[1])]
}
</script>

<style scoped lang="scss">
:deep(.el-range-editor.el-input__wrapper) {
  background: #0f0472a9 !important;
  color: #ffffff;
  border: 1px solid #93bee7 !important;
  line-height: 20px;
}
</style>
